package fr.univ.surveyonline.question.xmlbuilder;

import java.util.Date;

import fr.univ.surveyonline.model.Barometre;
import fr.univ.surveyonline.model.Contraintes;
import fr.univ.surveyonline.model.DateHelpers;
import fr.univ.surveyonline.model.Survey;
import fr.univ.surveyonline.model.allEnum.AgeEnum;
import fr.univ.surveyonline.model.allEnum.Categorie;
import fr.univ.surveyonline.model.allEnum.Region;
import fr.univ.surveyonline.model.allEnum.SexeEnum;

public class PropertiesToXml {

		private static String getDebut(String baliseValue) {
			return "<" + baliseValue + ">";
		}
		
		private static String getEnd(String baliseValue) {
			return "</" + baliseValue + ">";
		}
		
		private static String makeBalise(String baliseValue,Object contenu) {
			if (contenu == null) {
				contenu = "";
			}
			return "<" + baliseValue + ">" + contenu + "</" + baliseValue + ">";
		}
		
		public static String propertiesToXML(Survey survey) {
			String s = getDebut("properties");
			
			if (survey.getKey() == null) {
				s+=makeBalise("surveyid","");
			} else {
				s+=makeBalise("surveyid",survey.getKey().getId() + "");
			}
			s+=makeBalise("surveyName",survey.getName());
			
			Date beginDate = survey.getBeginDate();
			if (beginDate == null) {
				beginDate = DateHelpers.getTodayDate();
			}
			s+=makeBalise("dateDebut",DateHelpers.dateToString(beginDate));
			
			Date endDate = survey.getEndDate();
			if (endDate == null) {
				endDate = DateHelpers.getTodayDate();
			}
			s+=makeBalise("dateend",DateHelpers.dateToString(endDate));
			s+=makeBalise("remuneration",survey.getRemuneration());
			s+=makeBalise("isBarometre",survey.isBarometre() + "");
			
			Barometre b = survey.getBarometre();
			String st = ""; 
			if (b != null) {
				st = "" + b.getRepetition_frequence();
			}
			s+=makeBalise("repetition-frequence",st);
			
			st = ""; 
			if (b != null) {
				st = "" + b.getRepetition_number_futur();
			} 
			s+=makeBalise("repetition-number",st);

			Contraintes c  = survey.getContraintes();
			s += "<constraints>";
		
			s+= makeTab(c,"sexe",SexeEnum.values());
			s+= makeTab(c,"categorie",Categorie.values());
			s+= makeTab(c,"age",AgeEnum.values());
			s+= makeTab(c,"region",Region.values());

			s += "</constraints>";
			return s + getEnd("properties");
		}

		private static String makeTab(Contraintes c,String string, Object[] tableau) {
			String s = "";
			
			for (int i =0;i < tableau.length;i++) {
				Object o = tableau[i];
				s+= "<" + string + " name=\""  + o.toString()+ "\"";
				s+= " value=\"" + i + "\"";
				if (c.isRequired(o)) {
					s+= " min=\"" + makeNull(c.getMinimum(o)) + "\"";
					s+= " pour_cent=\"" + makeNull(c.getMinimumPourCent(o)) + "\"";
				}
				
				s+= "></" + string + ">";
			}
			return s;
		}

		private static String makeNull(Object o) {
			if (o == null) {
				return "";
			}
			return o.toString();
		}
}
